package com.ygqh.baby.service.impl;

import com.ygqh.baby.ao.*;
import com.ygqh.baby.exception.YgException;
import com.ygqh.baby.mapper.YgStoreMapper;
import com.ygqh.baby.mapper.YgSupplierMapper;
import com.ygqh.baby.model.SchJob;
import com.ygqh.baby.po.*;
import com.ygqh.baby.service.*;
import com.ygqh.baby.utils.DateConvertUtils;
import com.ygqh.baby.utils.ExceptionUtil;
import com.ygqh.baby.utils.MailUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.math.BigDecimal;
import java.util.*;

@Service
public class YgSupplierServiceImpl implements YgSupplierService {

    @Autowired
    private YgSupplierMapper ygSupplierMapper;
    @Autowired
    private YgStoreMapper ygStoreMapper;
    @Autowired
    private YgUserService ygUserService;
    @Autowired
    private YgUserBalanceService userBalanceService;
    @Autowired
    private YgProductService ygProductService;
    @Value("${default.head.url}")
    private String defaultHeadUrl;
    @Autowired
    private ScheduleJobService scheduleJobService;
    @Autowired
    private MailUtil mailUtil;
    @Autowired
    private YgSupplierReconciliationService ygSupplierReconciliationService;

    @Override
    public List<YgSupplier> find() {
        YgSupplierExample example = new YgSupplierExample();
        example.createCriteria().andStatusEqualTo(DataStatus.Valid.name());
        example.setOrderByClause("id desc");
        return ygSupplierMapper.selectByExample(example);
    }

    @Override
    public int findCount() {
        YgSupplierExample example = new YgSupplierExample();
        example.createCriteria().andStatusEqualTo(DataStatus.Valid.name());
        return ygSupplierMapper.countByExample(example);
    }

    @Override
    public YgSupplier findById(Long id) {
        return ygSupplierMapper.selectByPrimaryKey(id);
    }

    @Override
    public int save(YgSupplier ygSupplier) {
        ygSupplierMapper.insertSelective(ygSupplier);
        YgStore record = new YgStore();
        record.setCreateBy(ygSupplier.getCreateBy());
        record.setCreateTime(ygSupplier.getCreateTime());

        record.setSupplierid(ygSupplier.getId());
        record.setStatus(DataStatus.Valid);
        record.setStoreName(ygSupplier.getSupplierName());
        record.setStoreStatus("Active");
        ygStoreMapper.insert(record);
        if (ygSupplier.getSupplierType().equals("OnLine")) {
            // 创建用户
            YgUser ygUser = new YgUser();
            ygUser.setUserName(ygSupplier.getLoginName());
            ygUser.setPassword(ygSupplier.getLoginPassword());
            ygUser.setTelPhone(ygSupplier.getTelPhone());
            ygUser.setSourceCode(ygSupplier.getLoginName());
            ygUser.setBabyBirthday(null);
            ygUser.setBabyGender(null);
            ygUser.setGender(null);
            ygUser.setHeadImageUrl(defaultHeadUrl);
            ygUser.setNickName(ygSupplier.getLinkMan());
            ygUser.setCreateTime(new Date());
            ygUser.setIsSeller(true);
            ygUser.setUserType(UserType.Agent);
            ygUser.setForeverRate(new BigDecimal(0));
            ygUser.setShareRate(new BigDecimal(0));
            ygUserService.save(ygUser);

            YgUserBalance userBalance = new YgUserBalance();
            userBalance.setBalancePrice(new BigDecimal(0));
            userBalance.setCreateTime(new Date());
            userBalance.setFreezePrice(new BigDecimal(0));
            userBalance.setPreincomePrice(new BigDecimal(0));
            userBalance.setUserId(ygUser.getId());
            userBalance.setWithdrawPrice(new BigDecimal(0));
            userBalanceService.save(userBalance);
        }
        return 1;
    }

    @Override
    public int update(YgSupplier ygSupplier) {
        int row = ygSupplierMapper.updateByPrimaryKeySelective(ygSupplier);
        if (row > 0) {
            if (ygSupplier.getSupplierType().equals("OnLine")) {
                YgUser user = new YgUser();
                YgUser ygUser = ygUserService.findByUserName(ygSupplier.getLoginName());
                user.setId(ygUser.getId());
                user.setUserName(ygUser.getUserName());
                user.setPassword(ygSupplier.getLoginPassword());
                user.setSalt(ygUser.getSalt());
                ygUserService.update(user);
            }
        }
        return row;
    }

    @Override
    public ResultSet<YgSupplier> search(QueryInfo queryInfo, String q) {
        List<YgSupplier> list = ygSupplierMapper.selectSuper(queryInfo, q);
        int count = ygSupplierMapper.countSuper(q);
        return new ResultSet<>(count, list);
    }

    @Override
    public int deleteSoft(Long[] ids) {
        Assert.notEmpty(ids);
        YgSupplierExample example = new YgSupplierExample();
        example.createCriteria().andIdIn(Arrays.asList(ids));
        YgSupplier record = new YgSupplier();
        record.setStatus(DataStatus.Delete);

        return ygSupplierMapper.updateByExampleSelective(record, example);
    }

    @Override
    public int deleteSoft(Long id) {
        return this.deleteSoft(new Long[]{id});
    }

    @Override
    public int saveOrUpdate(YgSupplier ygSupplier) {
        int r;
        if (ygSupplier.getId() != null) {
            r = this.update(ygSupplier);
        } else {
            r = this.save(ygSupplier);
        }
//		if (r > 0 && ygSupplier.getSupplierType().equals("OnLine")) {
//			updateProductRebate(ygSupplier);
//		}
        return r;
    }

    private void updateProductRebate(YgSupplier ygSupplier) {
        if (ygSupplier != null && ygSupplier.getShareRate() != null && ygSupplier.getShareRate().compareTo(BigDecimal.valueOf(0)) > 0) {
            ygProductService.updateRebate(ygSupplier.getShareRate(), ygSupplier.getId());
        }
    }

    @Override
    public int checkSupplierName(String supplierName, Long id) {
        return ygSupplierMapper.checkSupplierName(supplierName, id);
    }

    @Override
    public int deleteSoft(YgSupplier supplier) {
        YgSupplierExample example = new YgSupplierExample();
        example.createCriteria().andIdEqualTo(supplier.getId());
        YgSupplier record = new YgSupplier();
        record.setStatus(DataStatus.Delete);
        record.setUpdateBy(supplier.getUpdateBy());
        record.setUpdateTime(supplier.getUpdateTime());
        ygSupplierMapper.updateByExampleSelective(record, example);
        YgStoreExample storeExample = new YgStoreExample();
        storeExample.createCriteria().andSupplieridEqualTo(supplier.getId());
        YgStore storeRecord = new YgStore();

        storeRecord.setStatus(DataStatus.Delete);
        storeRecord.setUpdateBy(supplier.getUpdateBy());
        storeRecord.setUpdateTime(supplier.getUpdateTime());
        ygStoreMapper.updateByExampleSelective(storeRecord, storeExample);
        deleteSupplierJob(supplier);
        return 1;
    }

    private void deleteSupplierJob(YgSupplier supplier) {
        YgQuartzJob jobMode = YgQuartzJob.Supplier;
        try {
            scheduleJobService.deleteJob(jobMode.getJobName(supplier.getId().toString()), jobMode.getJobGroup(), supplier.getUpdateBy());
        } catch (Exception e) {
            e.printStackTrace();
            try {
                mailUtil.sendWithHtml(new String[]{"sunshuo@yiigoo.com"}, "删除商家结算对账任务失败",
                        "[supplierId=" + supplier.getId().toString() + ", error=" + ExceptionUtil.getExceptionMsg(e) + "]");
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }
    }

    @Override
    public int checkLoginName(String loginName) {
        return ygSupplierMapper.checkLoginName(loginName);

    }

    @Override
    public YgSupplier findSupplierId(String userName) {
        YgSupplierExample example = new YgSupplierExample();
        example.createCriteria().andStatusEqualTo(DataStatus.Valid.name()).andLoginNameEqualTo(userName);
        List<YgSupplier> list = ygSupplierMapper.selectByExample(example);
        if (list.size() > 0)
            return list.get(0);
        return null;
    }

    /**
     * 异步添加商家结算任务
     *
     * @param supplierId
     */
    @Override
    public void updateSupplierScheduleJob(Long supplierId) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                YgSupplier ygSupplier = findById(supplierId);
                if (ygSupplier.getPaymentCycle() != null && ygSupplier.getPaymentCycle() > 0) { // 该商家启动结算
                    try {
                        addReconciliationJob(ygSupplier);
                    } catch (Exception e) {
                        e.printStackTrace();
                        try {
                            mailUtil.sendWithHtml(new String[]{"sunshuo@yiigoo.com"}, "添加商家结算对账任务失败",
                                    "[supplierId=" + ygSupplier.getId().toString() + ", error=" + ExceptionUtil.getExceptionMsg(e) + "]");
                        } catch (Exception e1) {
                            e1.printStackTrace();
                        }
                    }
                }
            }
        }).start();
    }

    private void addReconciliationJob(YgSupplier ygSupplier) {
        ygSupplierReconciliationService.addReconciliantionPastTime(ygSupplier);
        YgQuartzJob jobMode = YgQuartzJob.Supplier;
        String jobName = jobMode.getJobName(ygSupplier.getId().toString());
        List<ScheduleJob> jobList = scheduleJobService.findJobByJobNames(jobName);
        ScheduleJob job;
        Date now = new Date();
        if (CollectionUtils.isEmpty(jobList)) {
            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("supplierId", ygSupplier.getId());
            job = new SchJob(jobName, jobMode.getJobGroup(), "Houtai", null, null, "商家结算对账任务", jobMode.getSpringId(), jobMode.getMethodName(), dataMap);
            job.setCreateTime(now);
            job.setCreateBy(ygSupplier.getCreateBy());
        } else {
            job = jobList.get(0);
        }
        Date cronDate;
        int interval = ygSupplier.getPaymentCycle();
        if (interval >= 30) {
            cronDate = DateConvertUtils.addMonth(DateConvertUtils.getMonthStartDate(now), 1);
        } else {
            cronDate = DateConvertUtils.addDay(DateConvertUtils.getDateStart(now), interval);
        }
        job.setCronDate(cronDate);
        job.setCron(DateConvertUtils.format(cronDate, DateConvertUtils.DATE_FORMAT_CRON));
        job.setUpdateBy(ygSupplier.getUpdateBy());
        job.setUpdateTime(now);
        Message msg;
        if (job.getId() == null) {
            msg = scheduleJobService.addJobToSchedule(job);
        } else {
            msg = scheduleJobService.updateJobToSchedule(job);
        }
        if (msg.getType().equals(Message.Type.success)) {
            scheduleJobService.saveOrUpdate(job);
        } else {
            throw new YgException(msg.getContent());
        }
    }

    @Override
    public boolean isSyncWDT(Long id) {
        if (id == null) {
            return false;
        }
        return ygSupplierMapper.isSyncWDT(id);
    }

    @Override
    public List<YgSupplier> findListBySupplierName(List<String> supplierNameList) {
        Assert.notEmpty(supplierNameList, "商家名称 supplierNameList 不能为空");
        return ygSupplierMapper.selectListBySupplierName(supplierNameList);
    }

    @Override
    public List<YgSupplier> findListById(List<Long> idList) {
		if (CollectionUtils.isEmpty(idList)) {
			return new ArrayList<>();
		}
		YgSupplierExample example = new YgSupplierExample();
		example.createCriteria().andIdIn(idList).andStatusEqualTo(DataStatus.Valid.name());
        return ygSupplierMapper.selectByExample(example);
    }

    @Override
    public List<Long> findSupplierIdListWithTrade(Date startDate, Date endDate) {
        return ygSupplierMapper.selectSupplierIdListWithTrade(startDate,endDate);
    }
}
